var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var app = getApp();
var curPage;
var curScope;
var _onSearch;

function init({
  page,
  scope,
  onSearch
}) {
  curPage = page;
  curScope = scope || 'agentSearch';
  _onSearch = onSearch;

  _setData({
    q: '',
    isClear: false,
  })

  curPage['agentSearch.input'] = input;
  curPage['agentSearch.blur'] = blur;
  curPage['agentSearch.focus'] = focus;
  curPage['agentSearch.clear'] = clear;
  curPage['agentSearch.search'] = search;
}

function input(evt) {
  var val = evt.detail.value;
  var isClear = !!val;

  _setData({
    q: evt.detail.value,
    isClear,
  })
}

function blur(evt) {
  var val = evt.detail.value;

  if (!val) {
    _setData({
      isClear: false
    });
  }
}

function focus(evt) {
  _setData({
    isClear: true
  });
}

function clear() {
  _setData({
    q: '',
    isClear: false
  });
}

function search(evt) {
  var q = _getData('q').trim();
  var startT = new Date().getTime();

  if (!/^1[\d]{10}$/.test(q)) {
    return util.alert('您输入的手机号不正确');
  }

  _setData({
    submiting: true
  });

  ajax.P('/openapi/CUser/fetchOnedaiLiByPhone', {
    phone: q
  }, function(data) {
    var endT = new Date().getTime();

    setTimeout(() => {
      _setData({
        submiting: false
      });
      wx.navigateTo({
        url: '/pages/agentSearchInfo/index?info=' + JSON.stringify(data.result || {})
      });
    }, 600 - (endT - startT));
  }, function() {
    _setData({
      submiting: false
    });
  });
}

function _setData(data) {
  var obj = _getData();

  Object.assign(obj, data);

  curPage.setData({
    [`${curScope}`]: obj
  });
}

function _getData(key) {
  var data = curPage.data[`${curScope}`] || {};

  if (!key) {
    return data;
  } else {
    return data[key];
  }
}

module.exports = {
  init: init,
};